package com.handong.handserialprogram.module.singleperson;

import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.constants.ColorContant;
import com.handong.handserialprogram.constants.KeyConstant;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.model.status.FootRingStatus;
import com.handong.handserialprogram.module.base.EmergencyActivity;
import com.handong.handserialprogram.module.catchcriminal.CatchCriminalActivity;
import com.handong.handserialprogram.module.cofigring.showconfig.ShowConfigAcivity;
import com.handong.handserialprogram.ui.StepArcView;
import com.handong.handserialprogram.ui.UpdateDistanceDialog;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.SPUtil;
import com.handong.handserialprogram.voice.VoiceImpl;
import com.handong.handserialprogram.widget.SwitchButton;

public class SinglePersonActivity extends EmergencyActivity<SinglePersonPresenter> implements SinglePersonContract.View {

    private static final String TAG = SinglePersonActivity.class.getSimpleName();

    private TextView mShowSetDistance, mSinglePersonStatus, mRingElectricType, mRingLockType, mRingBrokenType, mRingVersion;
    private RelativeLayout mUpdateDistance, mDevicesInfo, mCatchCriminal, mCloseRingVoice, checkConfigLayout, mEmpower, mWithdraw, mcloseRingAlarm;
    private StepArcView mStepArcView;
    private SwitchButton mAlarmStatus, mEmpowerStatus, mWithdrawStatus, mCloseAlarmStatus;

    private UpdateDistanceDialog mDistanceDialog;

    private static final int STEP_TOTAL = 30;

    private static final int LOCK_TYPE_CLOSED = 0;
    private static final int LOCK_TYPE_OPEN = 1;
    private static final int LOCK_EMPOWER_OPEN = 2;

    private String mRingID = "";
    private String mPersonName;
    private GradientDrawable mPersonStatusDrawable;
    int status = FootRingStatus.NORMAL;

    private int mTestCount = 0;

    @Override
    protected int getContentViewID() {
        return R.layout.activity_single_person;
    }

    @Override
    protected SinglePersonPresenter createPresenter() {
        return new SinglePersonPresenter(this);
    }

    @Override
    protected void initViewByID() {
        mShowSetDistance = (TextView) findViewById(R.id.singlePersonSetDistance);
        mSinglePersonStatus = (TextView) findViewById(R.id.singlePersonStatus);
        mRingElectricType = (TextView) findViewById(R.id.ringElectricType);
        mRingBrokenType = (TextView) findViewById(R.id.ringBrokenType);
        mRingLockType = (TextView) findViewById(R.id.ringLockType);
        mStepArcView = (StepArcView) findViewById(R.id.singlePersonStep);

        mAlarmStatus = (SwitchButton) findViewById(R.id.singlePersonAlarmStatus);
        mEmpowerStatus = (SwitchButton) findViewById(R.id.sbEmpower);
        mWithdrawStatus = (SwitchButton) findViewById(R.id.sbWithdraw);
        mCloseAlarmStatus = (SwitchButton) findViewById(R.id.sbCloseAlarm);
        mRingVersion = (TextView) findViewById(R.id.footRingVersion);


        mUpdateDistance = (RelativeLayout) findViewById(R.id.updateDistance);
        mUpdateDistance.setOnClickListener(this);
        mDevicesInfo = (RelativeLayout) findViewById(R.id.deviceFootRingInfo);
        //mDevicesInfo.setOnClickListener(this);
        mCatchCriminal = (RelativeLayout) findViewById(R.id.catchCriminalMode);
        mCatchCriminal.setOnClickListener(this);
        mCloseRingVoice = (RelativeLayout) findViewById(R.id.closeRingAlarm);
        mCloseRingVoice.setOnClickListener(this);

        checkConfigLayout = findView(R.id.checkConfigLayout);
        checkConfigLayout.setOnClickListener(this);
        mEmpower = (RelativeLayout) findViewById(R.id.rlEmpower);
        mEmpower.setOnClickListener(this);

        mWithdraw = (RelativeLayout) findViewById(R.id.rlWithdraw);
        mWithdraw.setOnClickListener(this);

        //mEmpowerStatus.setOnClickListener(this);
    }

    @Override
    protected void initViewDataRes() {
        initHeaderLayout(false);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mPersonName = bundle.getString(KeyConstant.PERSON_NAME, "暂无");
            setCenterTitle(mPersonName);

            //boolean remind = SPUtil.getBooleanValue(mPersonName);
            //mAlarmStatus.setChecked(remind);
            boolean isEmpower = bundle.getBoolean(KeyConstant.EMPOWER_STATE);
            boolean isWithdraw = bundle.getBoolean(KeyConstant.WITHDRAW_STATE);
            boolean isWarnning = bundle.getBoolean(KeyConstant.WARNNING_STATE);
            int setDistance = bundle.getInt(KeyConstant.PERSON_SET_DISTANCE, 0);
            float distance = bundle.getFloat(KeyConstant.PERSON_DISTANCE, 0f);
            status = bundle.getInt(KeyConstant.RING_STATUS, 0);
            int brokenType = bundle.getInt(KeyConstant.LINE_STATUS, 0);
            int lockType = bundle.getInt(KeyConstant.LOCK_STATUS, 0);
            int ringPower = bundle.getInt(KeyConstant.ELECTRIC_STATUS, 0);
            String ringVersion = bundle.getString(KeyConstant.FOOT_VERSION, "未知");
            mRingVersion.setText(ringVersion);
            //设定距离。
            mShowSetDistance.setText(setDistance + "m");

            mStepArcView.setCurrentCount(STEP_TOTAL, distance, setDistance);
            //设置ID号。
            mRingID = bundle.getString(KeyConstant.PERSON_RING_ID, "");
            mPresenter.setFootRingId(mRingID);

            //当任务未结束时，提供紧急报警功能。
            boolean isVoiceRemind = SPUtil.getBooleanValue(SPUtil.RING_STATUS);
            mAlarmStatus.setChecked(isVoiceRemind);
            //mPresenter.setRemindSound(isVoiceRemind);
            mEmpowerStatus.setChecked(isEmpower);
            mWithdrawStatus.setChecked(isWithdraw);
            mCloseAlarmStatus.setChecked(isWarnning);


            if (status == FootRingStatus.ESCAPE) {
                this.mSinglePersonStatus.setText(R.string.ring_status_escape);
                this.mSinglePersonStatus.setTextColor(ColorContant.PERSON_ESCAPE);
                mCloseAlarmStatus.setEnabled(false);
                mEmpowerStatus.setEnabled(false);
                mWithdrawStatus.setEnabled(false);
            } else if (status == FootRingStatus.NODATA) {
                this.mSinglePersonStatus.setText(R.string.ring_status_nodata);
                this.mSinglePersonStatus.setTextColor(Color.parseColor("#C0C0C0"));
                mCloseAlarmStatus.setEnabled(false);
                mEmpowerStatus.setEnabled(false);
                mWithdrawStatus.setEnabled(false);
            } else {
                //if (0 == entity.getNoDataTime()){
                //    setOptionItem(String.valueOf(++mTestCount));
                //}
                mCloseAlarmStatus.setEnabled(true);
                mEmpowerStatus.setEnabled(true);
                mWithdrawStatus.setEnabled(true);
                this.mRingElectricType.setVisibility(View.VISIBLE);
                this.mRingLockType.setVisibility(View.VISIBLE);
                this.mRingBrokenType.setVisibility(View.VISIBLE);
                showBattery(ringPower);
                if (status == FootRingStatus.NORMAL && setDistance > distance) {
                    this.mSinglePersonStatus.setText(R.string.ring_status_normal);
                } else {
                    if (status == FootRingStatus.NORMAL) {
                        this.mSinglePersonStatus.setText(R.string.ring_status_exception);
                    } else {
                        this.mSinglePersonStatus.setText(R.string.ring_status_week);
                    }

                    this.mSinglePersonStatus.setTextColor(ColorContant.PERSON_EXCEPTION);
                }
                if (lockType == LOCK_TYPE_CLOSED) {
                    this.mRingLockType.setText(R.string.ring_lock_closed);
                    this.mRingLockType.setTextColor(ColorContant.DEFAULT_TEXT_COLOR);
                } else if (lockType == LOCK_TYPE_OPEN) {
                    this.mRingLockType.setText(R.string.ring_lock_open);
                    this.mRingLockType.setTextColor(ColorContant.PERSON_ESCAPE);
                } else if (lockType == LOCK_EMPOWER_OPEN) {
                    this.mRingLockType.setText(R.string.ring_lock_open);
                    this.mRingLockType.setTextColor(ColorContant.DEFAULT_TEXT_COLOR);
                }
                if (brokenType == 0) {
                    this.mRingBrokenType.setText("锁链:通");
                    this.mRingBrokenType.setTextColor(ColorContant.DEFAULT_TEXT_COLOR);
                } else if (brokenType == 1) {
                    this.mRingBrokenType.setText("锁链:断");
                    this.mRingBrokenType.setTextColor(ColorContant.PERSON_ESCAPE);
                }
            }

        }
        mCloseAlarmStatus.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {
                    mPresenter.closeRingEmergency(mRingID);
                } else {
                    mPresenter.openRingEmergency(mRingID);
                }

                //mPresenter.setRemindSound(isChecked);
                // SPUtil.putBooleanValue(SPUtil.RING_STATUS, isChecked);
            }
        });
        mAlarmStatus.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {
                    AppUtil.showShortToast(SinglePersonActivity.this.getApplicationContext(), "提醒功能已开启");
                } else {
                    AppUtil.showShortToast(SinglePersonActivity.this.getApplicationContext(), "已关闭提醒功能");
                    VoiceImpl impl = VoiceImpl.getInstance(SinglePersonActivity.this);
                    impl.releaseRes();
                }
                mPresenter.setRemindSound(isChecked);
                SPUtil.putBooleanValue(SPUtil.RING_STATUS, isChecked);
            }
        });
        mEmpowerStatus.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (mPresenter.setEmpowerStatus(isChecked)) {
                    if (isChecked) {
                        AppUtil.showShortToast(SinglePersonActivity.this.getApplicationContext(), "授权成功,可以打开脚环");
                        mPresenter.setLockIsStopAlarm(mRingID, true);

                    } else {
                        AppUtil.showShortToast(SinglePersonActivity.this.getApplicationContext(), "关闭授权成功，打开脚环上传报警到管理平台");
                        mPresenter.setLockIsStopAlarm(mRingID, false);
                    }
                } else {
                    AppUtil.showShortToast(SinglePersonActivity.this.getApplicationContext(), "操作失败");
                }
            }
        });

        mWithdrawStatus.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (mPresenter.setWithdrawStatus(isChecked)) {
                    if (isChecked) {
                        AppUtil.showShortToast(SinglePersonActivity.this.getApplicationContext(), "设置临时撤防成功,该脚环数据将不会上传到管理平台");

                    } else {
                        AppUtil.showShortToast(SinglePersonActivity.this.getApplicationContext(), "关闭临时撤防成功，该脚环数据将上传到管理平台");
                    }
                } else {
                    AppUtil.showShortToast(SinglePersonActivity.this.getApplicationContext(), "操作失败");
                }
            }
        });
    }

    private long mLastClickTime = 0;
    public static final long TIME_INTERVAL = 500L;

    @Override
    public void onClick(View v) {
        long nowTime = System.currentTimeMillis();
        if (nowTime - mLastClickTime > TIME_INTERVAL) {
            switch (v.getId()) {
                case R.id.rlEmpower:

                case R.id.closeRingAlarm://关闭警报
                case R.id.rlWithdraw:
                    if (status == FootRingStatus.ESCAPE) {

                        MaterialDialog dialog = null;
                        dialog = new MaterialDialog.Builder(this)
                                .content("犯人已脱离管控，无法对其进行操作！")
                                .positiveColorRes(R.color.back_ground_green)
                                .positiveText(R.string.dialog_positive_text)
                                .build();
                        dialog.show();
                    }
                    break;
                case R.id.headerBackLayout:
                    finish();
                    break;

                case R.id.updateDistance://设置距离
                    if (status != FootRingStatus.ESCAPE) {
                        showUpdateDistanceDialog();
                    } else {
                        MaterialDialog dialog = null;
                        dialog = new MaterialDialog.Builder(this)
                                .content("犯人已脱离管控，无法对其进行操作！")
                                .positiveColorRes(R.color.back_ground_green)
                                .positiveText(R.string.dialog_positive_text)
                                .build();
                        dialog.show();
                    }
                    break;

                case R.id.deviceFootRingInfo://设备信息
                    break;

                case R.id.catchCriminalMode://追逃模式
                    Bundle bundle = new Bundle();
                    bundle.putString(KeyConstant.PERSON_RING_ID, mRingID);
                    bundle.putString(KeyConstant.PERSON_NAME, mPersonName);
                    bundle.putBoolean(KeyConstant.PERSON_STATUS, mPresenter.isEscape());
                    openActivity(CatchCriminalActivity.class, bundle);
                    break;
                case R.id.checkConfigLayout://查看脚环配置
                    Bundle bd = new Bundle();
                    bd.putString(KeyConstant.PERSON_RING_ID, mRingID);
                    openActivity(ShowConfigAcivity.class, bd);
                    break;


                default:
                    super.onClick(v);
                    break;
            }
        }
    }

    /**
     * 设置距离
     */
    public void showUpdateDistanceDialog() {
        if (mDistanceDialog == null) {
            mDistanceDialog = UpdateDistanceDialog.createDialog(getSupportFragmentManager(), new UpdateDistanceDialog.BtnSureListener() {
                @Override
                public void btnSure(String s) {
                    dealUpdateDistance(s);
                }
            });

        }
        if (!mDistanceDialog.isAdded()) {
            mDistanceDialog.show();
        }

    }

    /**
     * 设置距离
     */
    public void dealUpdateDistance(String distance) {
        this.mDistanceDialog.dismiss();
        showLoadDialog("正在修改设定距离...");
        mPresenter.updateRingSetDistance(this.mRingID, distance);
    }


    @Override
    public void updateDistanceInfo(FootRingNewEntity entity) {
        if (entity == null) {
            //AppUtil.showShortToast(this, "获取脚环信息失败");
            finish();
            return;
        }
        if (entity.getNoDataTime() == FootRingNewEntity.STATE_NORMAL_LIMIT) {
            //AppUtil.showShortToast(this, "获取脚环信息失败");
        }
        mRingVersion.setText(entity.getVersion());
        int setDistance = entity.getSetRingDistance();
        float distance = entity.getActualRingDistance();
        this.mShowSetDistance.setText(setDistance + "m");
        this.mSinglePersonStatus.setTextColor(ColorContant.SINGLE_PERSON_TEXT_COLOR);
        status = entity.getStatus();

        if (status == FootRingStatus.ESCAPE) {
            this.mSinglePersonStatus.setText(R.string.ring_status_escape);
            this.mSinglePersonStatus.setTextColor(ColorContant.PERSON_ESCAPE);
            mCloseAlarmStatus.setEnabled(false);
            mEmpowerStatus.setEnabled(false);
            mWithdrawStatus.setEnabled(false);
            this.mRingElectricType.setVisibility(View.GONE);
            this.mRingLockType.setVisibility(View.GONE);
            this.mRingBrokenType.setVisibility(View.GONE);
        } else if (status == FootRingStatus.NODATA) {
            this.mSinglePersonStatus.setText(R.string.ring_status_nodata);
            this.mSinglePersonStatus.setTextColor(Color.parseColor("#C0C0C0"));
            mCloseAlarmStatus.setEnabled(false);
            mEmpowerStatus.setEnabled(false);
            mWithdrawStatus.setEnabled(false);
            this.mRingElectricType.setVisibility(View.GONE);
            this.mRingLockType.setVisibility(View.GONE);
            this.mRingBrokenType.setVisibility(View.GONE);

        } else {
            //if (0 == entity.getNoDataTime()){
            //    setOptionItem(String.valueOf(++mTestCount));
            //}
            mCloseAlarmStatus.setEnabled(true);
            mEmpowerStatus.setEnabled(true);
            mWithdrawStatus.setEnabled(true);
            this.mRingElectricType.setVisibility(View.VISIBLE);
            this.mRingLockType.setVisibility(View.VISIBLE);
            this.mRingBrokenType.setVisibility(View.VISIBLE);
            showBattery(entity.getTruePower());
            if (entity.getStatus() == FootRingStatus.NORMAL && setDistance > distance) {
                this.mSinglePersonStatus.setText(R.string.ring_status_normal);
            } else {
                if (status == FootRingStatus.NORMAL) {
                    this.mSinglePersonStatus.setText(R.string.ring_status_exception);
                } else {
                    this.mSinglePersonStatus.setText(R.string.ring_status_week);
                }
                this.mSinglePersonStatus.setTextColor(ColorContant.PERSON_EXCEPTION);
            }
            if (entity.getLockType() == LOCK_TYPE_CLOSED) {
                this.mRingLockType.setText(R.string.ring_lock_closed);
                this.mRingLockType.setTextColor(ColorContant.DEFAULT_TEXT_COLOR);
            } else if (entity.getLockType() == LOCK_TYPE_OPEN) {
                this.mRingLockType.setText(R.string.ring_lock_open);
                this.mRingLockType.setTextColor(ColorContant.PERSON_ESCAPE);
            } else if (entity.getLockType() == LOCK_EMPOWER_OPEN) {
                this.mRingLockType.setText(R.string.ring_lock_open);
                this.mRingLockType.setTextColor(ColorContant.DEFAULT_TEXT_COLOR);
            }
            if (entity.getBrokenType() == 0) {
                this.mRingBrokenType.setText("锁链:通");
                this.mRingBrokenType.setTextColor(ColorContant.DEFAULT_TEXT_COLOR);
            } else if (entity.getBrokenType() == 1) {
                this.mRingBrokenType.setText("锁链:断");
                this.mRingBrokenType.setTextColor(ColorContant.PERSON_ESCAPE);
            }
        }
        if ((!mCloseAlarmStatus.isChecked() && entity.isStopAlarm()) || (mCloseAlarmStatus.isChecked() && !entity.isStopAlarm())) {
            mCloseAlarmStatus.setEnabled(true);
            mCloseAlarmStatus.setChecked(entity.isStopAlarm());
            if (status == FootRingStatus.ESCAPE) {
                mCloseAlarmStatus.setEnabled(false);
            }
        }
        this.mStepArcView.setCurrentCount(STEP_TOTAL, distance, setDistance);
    }

    private void showBattery(int battery) {
        if (0 > battery) {
            return;
        }
//        int temp = 0;
//        if (battery >= 175) {//4.15
//            temp = 100;
//        } else if (battery >= 161) {//90 9
//            temp = 90;
//        } else if (battery >= 148) {//80 9
//            temp = 80;
//        } else if (battery >= 133) {//70 10
//            temp = 70;
//        } else if (battery >= 118) {//60 10
//            temp = 60;
//        } else if (battery >= 102) {//50 11
//            temp = 50;
//        }else if (battery >= 89) {//40 3.6
//            temp = 40;
//        }else if (battery >= 74) {//30 12
//            temp = 30;
//        }else if (battery >= 59) {//20 13
//            temp = 20;
//        }else if (battery > 52) {//10 3.34
//            temp = 10;
//        }else {//5
//            temp = 0;
//        }


//        if (battery>162)
//        {
//            temp = 100;
//        }
//        else{
//            temp=battery;
//        }

//        if(battery<40)
//        if(battery<100)
//        {
//            mRingElectricType.setText("电量:低");
//        }
//        else{

//        }

//        if (battery < 95) {
//            mRingElectricType.setTextColor(ColorContant.PERSON_ESCAPE);
//        } else {
//            mRingElectricType.setTextColor(ColorContant.DEFAULT_TEXT_COLOR);
//        }
        if (battery < 30) {

            mRingElectricType.setTextColor(ColorContant.PERSON_ESCAPE);
        } else {

            mRingElectricType.setTextColor(ColorContant.DEFAULT_TEXT_COLOR);
        }
        mRingElectricType.setText("电量:" + battery + "%");
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.anim_no, R.anim.push_right_out);
    }

    @Override
    protected void onDestroy() {
        if (mDistanceDialog != null) {
            mDistanceDialog.dismissAllowingStateLoss();
            mDistanceDialog = null;
        }
        super.onDestroy();
    }
}
